package me.yidasanqian.crowdfunding.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author Linyu Chen
 */
@Configuration
public class DruidConfiguration {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    /**
     * 注册一个StatViewServlet
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean DruidStatView() {

        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 白名单：
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // IP黑名单 (存在共同时，deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        //servletRegistrationBean.addInitParameter("deny", "192.168.1.7");
        // 登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername", "druid_admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123123");
        // 是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable", "false");

        return servletRegistrationBean;

    }


    /**
     * 注册一个：DruidWebStatFilter
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean DruidWebStatFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        // 添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        // session最大数量配置, 缺省1000
        filterRegistrationBean.addInitParameter("sessionStatMaxCount", "1000");
        // 开启session统计功能
        filterRegistrationBean.addInitParameter("sessionStatEnable", "true");
        // 使得druid能够知道当前的session的用户是谁.根据需要，把其中的xxx.user修改为你user信息保存在session中的sessionName.
        // 注意：如果你session中保存的是非string类型的对象，需要重载toString方法。
        filterRegistrationBean.addInitParameter("principalSessionName", "userinfo");
        // 能够监控单个url调用的sql列表
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        return filterRegistrationBean;
    }
}
